
package com.fsoft.core.dict.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fsoft.core.common.QueryParam;
import com.fsoft.core.common.base.service.impl.BaseServiceImpl;
import com.fsoft.core.dict.entity.SysDict;
import com.fsoft.core.dict.service.SysDictItemService;
import com.fsoft.core.dict.service.SysDictService;
import com.fsoft.core.utils.DateTimeUtils;
import com.fsoft.core.utils.OgnlUtils;

/**
 * F-Soft 数据字典管理服务<br>
 * @package com.fsoft.core.dict.service.impl
 * @author Fish
 * @email it.fish2010@foxmail.com
 * @date 2020-02-15
 * @CopyRight © F-Soft
 **/
@Transactional
@Service("sysDictService")
public class SysDictServiceImpl extends BaseServiceImpl<SysDict> implements SysDictService {
	@Autowired
	private SysDictItemService itemService;

	/***
	 * 根据字典编码查询字典：验证字典是否存在
	 * @author licheng
	 * @date 2021-04-09
	 * @param code
	 * @return
	 * @throws Exception
	 */
	protected SysDict getEntityByCode(String code) throws Exception {
		SysDict dict = new SysDict();
		dict.setCode(code);
		QueryParam query = new QueryParam(dict);
		List<SysDict> dicts = findList(query);
		return OgnlUtils.isEmpty(dicts) ? null : dicts.get(0);
	}

	@Override
	public int save(SysDict param) throws Exception {
		SysDict entity = getEntityByCode(param.getCode());
		if (OgnlUtils.isNotEmpty(entity))
			throw new Exception("字典编码[" + param.getCode() + "]已存在！");
		return super.save(param);
	}

	@Override
	public int modify(SysDict param) throws Exception {
		if (OgnlUtils.isEmpty(param.getModifyTime()))
			param.setModifyTime(DateTimeUtils.getNowTime());
		if (StringUtils.isNotBlank(param.getCode())) {
			SysDict entity = getEntityByCode(param.getCode());
			if (OgnlUtils.isNotEmpty(entity) && !StringUtils.equals(entity.getId(), param.getId()))
				throw new Exception("字典编码[" + param.getCode() + "]已被字典[" + entity.getName() + "]使用!");
		}
		return super.modify(param);
	}

	/**
	 * 删除字典操作，需要级联删除字典配置项
	 */
	@Override
	public int remove(String rwid) throws Exception {
		itemService.removeByDict(rwid);
		return super.remove(rwid);
	}

	@Override
	public int removeBatch(List<String> ids) throws Exception {
		if (OgnlUtils.isNotEmpty(ids) && ids.size() == 1) {
			return remove(ids.get(0));
		}
		itemService.removeByDict(ids);
		return super.removeBatch(ids);
	}
}
